/**
 * Copyright (C)  Gadglet .
 *
 * This file is part of Gadglet
 *
 * Gadglet is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Gadglet is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Gadglet. If not, see <http://www.gnu.org/licenses/>.
 */

package com.gadglet.client.gwt.core.ui;

import java.util.ArrayList;

import com.gadglet.client.gwt.GadgetNativeUtils;
import com.gadglet.client.gwt.GadgetUtils;
import com.gadglet.client.gwt.core.GadgletQuery;
import com.gadglet.client.gwt.core.GadgletRequest;
import com.gadglet.client.gwt.core.GadgletResponse;
import com.gadglet.client.gwt.ui.DebugDialogBox;
import com.gadglet.client.gwt.ui.UIUtils;
import com.gadglet.params.ProfileFields;
import com.gadglet.params.ReqActionTypes;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.gadgets.client.impl.PreferencesUtil;
import com.google.gwt.gadgets.client.osapi.Callback;
import com.google.gwt.gadgets.client.osapi.OsapiCollection;
import com.google.gwt.gadgets.client.osapi.OsapiError;
import com.google.gwt.gadgets.client.osapi.OsapiRequest;
import com.google.gwt.gadgets.client.osapi.people.GetPeopleRequestBuilder;
import com.google.gwt.gadgets.client.osapi.people.PeopleService;
import com.google.gwt.gadgets.client.osapi.people.Person;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;





/**
 * UI class that present the user a list of his friends from the OpenSocial Container. 
 * The user will be able to "invite" those friends to join him on the Gadget service
 *
 */
public class LocalFriendsPanel {

	DebugDialogBox debug = DebugDialogBox.getErrorNotifier();
	
	protected final PreferencesUtil prefs = PreferencesUtil.nativeInitPrefs();
	
	private final VerticalPanel localFrindsContainer = new VerticalPanel();
	private final VerticalPanel localFrindsList = new VerticalPanel();
	private final ArrayList <LocalFriendItem> localFriendItem = new ArrayList <LocalFriendItem>();
	private static LocalFriendsPanel friendsPanel;
	
	private final HTML messageDispaly = new HTML();
	final GadgletQuery inviteQry = new GadgletQuery();
	
	final InviteRequest inviteRequest = new InviteRequest(
			inviteQry);
	
	public static LocalFriendsPanel getFriendsPanel() {
		if (friendsPanel == null) {
			friendsPanel = new LocalFriendsPanel();
		}
		return friendsPanel;
	}
	
	VerticalPanel getLocalFrindsContainer(){
		return this.localFrindsContainer;
	}


	
	
	private LocalFriendsPanel() {
		
		inviteQry.setRequestAction(ReqActionTypes.INVITE_FRIEND);
		Label localFrindsLabel = new Label();
		localFrindsLabel.setWidth("250px");

		localFrindsLabel.setStylePrimaryName("friendsLabel");
		localFrindsLabel.setText(prefs.getMsg("gadgetLabelLocalFriends") );
		localFrindsContainer.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		localFrindsContainer.add(localFrindsLabel);
		localFrindsContainer.add(messageDispaly);
		localFrindsContainer.add(localFrindsList);
				
	}

	public void viewLocalFriends() {
		messageDispaly.setText("");
		messageDispaly.setVisible(false);
		localFrindsList.clear();

		try {
			
				
			PeopleService peopleService = PeopleService.getInstance();
			
			GetPeopleRequestBuilder builder = peopleService
					.newGetViewersFriendsRequestBuilder();
			
			builder.setFields("thumbnailUrl","email","id","name");
			
			if (GadgetUtils.isCanvasView())
				builder.setCount(100);
			else
				builder.setCount(20);

			OsapiRequest<OsapiCollection<Person>> friends = builder.build();

			Callback<OsapiCollection<Person>> callback = new Callback<OsapiCollection<Person>>() {
				@Override
				public void onFail(OsapiError error) {

					if (error.getCode() == 403) {
						messageDispaly.setVisible(true);
						messageDispaly.setHTML(prefs
								.getMsg("gadgetMsgFriendsAccessError"));
					}

				}
			

				@Override
				public void onSuccess(OsapiCollection<Person> collection) {
					Iterable<Person> iter = collection.iterable();
				
					for (Person person : iter) 
					{
				
						if (person.getId()!=null)
						{
							LocalFriendItem item = new LocalFriendItem(person);
							localFriendItem.add(item);
							localFrindsList.add(item.getPersonItem());
							
						}
					}
					
					if(localFriendItem.size()<1)
					{
						messageDispaly.setVisible(true);
						messageDispaly.setHTML(prefs
								.getMsg("gadgetMsgFriendsLocalListEmpty"));
					}

				}
			};

			friends.execute(callback);
		} catch (Exception e) {
			debug.showError(104, e.getMessage());
		}
		
	
	}

	
	private class LocalFriendItem{
		private Person person;
		
		LocalFriendItem (Person person){
			this.person = person;
		}
		
		Person getPerson(){
			return this.person;
		}
		
		HorizontalPanel getPersonItem(){
			HorizontalPanel item = new HorizontalPanel();
			
			item.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
			item.setHeight("40px");
			HTML displayName =null;
			displayName = new HTML(person.getDisplayName());
			item.add(displayName);
			item.setCellWidth(displayName, "100px");
			item.add(UIUtils.getSpace());
			
			if(person.getThumbnailUrl()!=null){
				Image img = new Image(person.getThumbnailUrl());
				img.setPixelSize(30, 30);
				item.add(img);
			}
			else
			{
				HTML replaceImg = new HTML();
				item.setCellWidth(replaceImg, "30px");
			}
			item.add(UIUtils.getSpace());	
			
			final Button inviteButton = new Button(prefs.getMsg("gadgetLabelInvite"));
			inviteButton.addClickHandler(new ClickHandler() {
				@Override
				public void onClick(ClickEvent event) {
					inviteQry.clearParamList();
					inviteQry.addParam(ProfileFields.PROFILE_FRIEND_ID.getParamName(),getPerson().getId() );
					inviteRequest.makeRequest();
					try {
						GadgetNativeUtils.requestShareApp(getPerson().getId(),prefs.getMsg("gadgetMsgFriendsInvitationNote"));
					} catch (Exception e) {
						// TODO Auto-generated catch block
						debug.showError(105,e.getMessage());
					}
					inviteButton.setEnabled(false);
				}
			});
			
			item.add(inviteButton);
			
			return item;
		}
		
		
	}
	
	
	
	public class InviteRequest extends GadgletRequest {
		InviteRequest(GadgletQuery req) {
			super(req);
		}

		@Override
		protected void processResults(GadgletResponse data) {
			GadgletResponse jResponse = data;

			if (jResponse.isSuccessful()) {
		
				

			} else {

				debug.showError(101, jResponse.getError());
			}

		}
	}
	
}
